package org.mch.start;

import java.awt.EventQueue;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.PropertyConfigurator;
import org.mch.comm.itf.IMLogger;
import org.mch.main.MCHFrame;

import com.mch.main.common.MEnv;
import com.mch.ui.cons.MStyle;

public class MCHStart {
	private final static IMLogger log = new MUILogger(MCHStart.class);
	private final static Properties Prop = new Properties();

	public static void main(String[] args) {
		MStyle.initAllStyle();

		loadLogConfig();
		loadMCHConfig();

		log.debug("Start......");

		start();
	}

	private static void start() {
		if (Prop.isEmpty()) {
			// UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
			// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					MEnv.MAINFRAME = new MCHFrame();
					// MCHFrame.frame.showMax();

					// Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
					// Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
					// int screenWidth = screenSize.width / 2; // 获取屏幕的宽
					// int screenHeight = screenSize.height / 2; // 获取屏幕的高
					// int height = MCHFrame.frame.getHeight();
					// int width = MCHFrame.frame.getWidth();
					// // 移动TestFrame至居中位置
					// MCHFrame.frame.setLocation(screenWidth - width / 2,
					// screenHeight - height / 2 - 50);

					sleep(2);
					MEnv.MAINFRAME.setVisible(true);
				}
			});
		} else {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					String className = Prop.getProperty("start");
					Object obj = null;
					try {
						obj = Class.forName(className).newInstance();
					} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
						log.debug(e);
					}
					if (obj != null && obj instanceof ItfStart) {
						((ItfStart) obj).start();
					} else {
						log.debug("自定义启动类，需要实现 org.mch.start.ItfStart 接口！");
					}
				}
			});
		}
	}

	/**
	 * 加载日志配置信息
	 */
	public static void loadLogConfig() {
		URL log4jUrl = MCHFrame.class.getResource("/resource/config/log4j.properties");
		String log4jFilePath = "file:" + log4jUrl.getFile();

		System.setProperty("log4j.configuration", log4jFilePath);

		/*
		 * Log4j加载自定义的配置文件；
		 */
		PropertyConfigurator.configure(log4jUrl);
	}

	/**
	 * 加载自定义配置信息
	 */
	public static void loadMCHConfig() {
		InputStream mchConfigIS = MCHFrame.class.getResourceAsStream("/resource/config/mch.properties");

		try {
			Prop.load(mchConfigIS);
		} catch (IOException e) {
			log.debug(e);
			log.debug("读取 mch.properties 失败，执行默认启动！");
		}
	}

	public static void sleep(int second) {
		try {
			Thread.sleep(second * 1000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
